package com.afm.prj.hangman;

import java.util.ArrayList;

import android.content.res.Resources;
import android.content.Context;
import android.util.Log;
import android.content.Intent;
public class WordManager {
	
	private String 		thisWord, tempWord;
	private String[] 	wordArray;
	private Resources 	res;
	private char[] letterArray, letterArray2;



	// Constructor gets context in order to properly use Android-specific calls.
	public WordManager(Context context) { res = context.getResources();}
	
	// Set the word (used for intents)
	public void setWord(String word) { thisWord = word; }
	
	// Get word
	public String getWord() { return thisWord; }
	

	
	// Get a new random word from file arrays.xml.
	public void CreateNewWord(int language) {
		wordArray = res.getStringArray(language);
		int randomWordIndex = (int) (Math.random() * wordArray.length);
		thisWord = wordArray[randomWordIndex];	
		tempWord = thisWord;
	
		// This will be used in getDisplayedWord() later.
		letterArray = new char[thisWord.length()];
		letterArray2 = new char[thisWord.length()];
		for(int i = 0; i < letterArray.length; i++) {
			letterArray[i] = thisWord.charAt(i);
			letterArray2[i] = '_';
		}
		
	}

	
	// Check if user-inputed letter exists in our word.
	public boolean DoesLetterExist(char l) {		
		for(int i = 0; i < thisWord.length(); i++)
			if(thisWord.charAt(i) == l)  return true; 	
		
		return false;
	}	
	
	public int CountDistinctCharacters() {
		char a  		= ' ';
		int count  		= thisWord.length();
		ArrayList<Character> collected = new ArrayList<Character>();

		// For every character of the word.
		for(int i = 0; i < thisWord.length(); i++) {
			boolean exists  = false;
			a = thisWord.charAt(i);
			
			// Check if it has been encountered before.
			for(int ii = 0; ii < collected.size(); ii++) {	
				if(collected.get(ii) == a) {
					exists = true;
				}
			}
			// Word doesn't exist in array, collect it.
			if(!exists) { collected.add(a); }
		}
		count = collected.size();
		return count;
	}	
	
	public String getDisplayedWord(ArrayList<Character> list) {
		String displayedWord = "";

		if(list.size() > 0) 
		{
			for(int i = 0; i < letterArray.length; i++) {
			
		        for(int ii = 0; ii < list.size(); ii++) {
		        	if(letterArray[i] == list.get(ii)) {
		        		letterArray2[i] = letterArray[i];
		        	}	
		        }
	        }
		   
			for(int i = 0; i < letterArray2.length; i++) {
				displayedWord = displayedWord + " " + letterArray2[i];
			}
			
		} else {
	        for(int i = 0; i < thisWord.length(); i++) {
	        	if(i == 0) 	displayedWord = "_";
	        	else 		displayedWord = displayedWord + " _";
	        }
		}

    return displayedWord;
	}
}